package de.wolvan.window;

import javax.swing.*;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Iterator;

import de.wolvan.main.main;
import de.wolvan.tools.*;
import de.wolvan.references.*;
import de.wolvan.interfaces.*;

public class ChatWindow extends JFrame implements ActionListener {
	
	private JButton sendMsg;
	private JButton exitChat;
	
	private JButton addFriend;
	private JButton removeFriend;
	
	private JTextField msg;
	
	private static JList list;
	public static JList users;
	
	public static DefaultListModel listModel = new DefaultListModel();
	public static DefaultListModel listModel2 = new DefaultListModel();
	public static DefaultListModel userListModel = new DefaultListModel();
	
	public static ListSelectionListener listSelectionListener;
	
	public static HashMap<String, Boolean> map = new HashMap();
	public static HashMap<String, Boolean> newMsg = new HashMap();
	public static HashMap<String, Boolean> noFriend = new HashMap();
	
	private JScrollPane scrollPane;
	private JScrollPane userScrollPane;
	
	public static ChatWindow frame;
	
	public static void renderGUI() {
		
		frame = new ChatWindow("Chat");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(800,400);
		frame.setLayout(null);
		frame.setVisible(true);
		
	}
	
	public ChatWindow(String title) {
		super(title);
		
		listSelectionListener = new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent arg0) {
				
				if(!(users.getSelectedValue() == null)) {
					String Users = "";
					for(int i = 0; i < users.getSelectedValues().length; i++) {
						if(newMsg.get(users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", ""))) {
							newMsg.put(users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", ""), false);
							redrawUserList(-1);
						}
						if(i != users.getSelectedValues().length - 1)  {
							Users += users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + ", ";
						} else {
							Users += users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "");
						}
					}
					System.out.println("New Selected User(s): " + Users);
					drawChatList();
					frame.setTitle("Chat - " + Users);
					
				}
				
			}
			
		};
		
		sendMsg = new JButton("Send Message");
		sendMsg.setBounds(10, 10, 160, 40);
		sendMsg.addActionListener(this);
		sendMsg.setFocusable(false);
		add(sendMsg);
		
		exitChat = new JButton("Exit Chat");
		exitChat.setBounds(210, 10, 160, 40);
		exitChat.addActionListener(this);
		exitChat.setFocusable(false);
		add(exitChat);
		
		addFriend = new JButton("Add friend");
		addFriend.setBounds(380,310,190,40);
		addFriend.addActionListener(this);
		addFriend.setFocusable(false);
		add(addFriend);
		
		removeFriend = new JButton("Remove friend");
		removeFriend.setBounds(580,310,190,40);
		removeFriend.addActionListener(this);
		removeFriend.setFocusable(false);
		add(removeFriend);
		
		msg = new JTextField("");
		msg.setBounds(10, 60, 360, 20);
		msg.addActionListener(this);
		add(msg);
		
		list = new JList(listModel2);
		list.setBounds(10,90,360,260);
		list.setFocusable(false);
		add(list);
		
		scrollPane = new JScrollPane(list);
		scrollPane.setBounds(10,90,360,260);
		scrollPane.setFocusable(false);
		add(scrollPane);
		
		users = new JList(userListModel);
		users.setBounds(380,10,390,290);
		users.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		users.addListSelectionListener(listSelectionListener);
		users.setFocusable(false);
		add(users);
		
		userScrollPane = new JScrollPane(users);
		userScrollPane.setBounds(380,10,390,290);
		userScrollPane.setFocusable(false);
		add(userScrollPane);
	}
	
	public static void redrawUserList(int index) {
		int[] indices = null;
		if(users != null)  {
			indices = users.getSelectedIndices();
		}
		userListModel.clear();
		Iterator iterator = map.keySet().iterator();
	    while (iterator.hasNext()) {
	      String key = (String) iterator.next();
	      String nE = "";
	      if(noFriend.get(key)) {
		      if(newMsg.get(key)) {
			      if(map.get(key)) {
				      nE = key + " - No Friend" + " - New Message";
			      } else {
				      nE = key + " - No Friend" + " - New Message";
			      }
		      } else {
		    	  if(map.get(key)) {
				      nE = key + " - No Friend";
			      } else {
				      nE = key + " - No Friend";
			      } 
		      }  
	      } else {
		      if(newMsg.get(key)) {
			      if(map.get(key)) {
				      nE = key + " - Online" + " - New Message";
			      } else {
				      nE = key + " - Offline" + " - New Messag";
			      }
		      } else {
		    	  if(map.get(key)) {
				      nE = key + " - Online";
			      } else {
				      nE = key + " - Offline";
			      } 
		      }
	      }
	      if(!nE.equals("null - Offline")) {
	    	  userListModel.addElement(nE);
	      }
	    }
	    if(users != null) {
	    	users.setSelectedIndices(indices);
	    }
	}
	
	public static void drawChatList() {
		listModel2.clear();
		for(int i = 0; i < listModel.getSize(); i++) {
			String[] splits = listModel.getElementAt(i).toString().split(";@<-toUser@@message->@;");
			if(!(users.getSelectedValue() == null)) {
				for(int j = 0; j < users.getSelectedValues().length; j++) {
					if(listModel.getElementAt(i).toString().startsWith(users.getSelectedValues()[j].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "").replace(" - No Friend", ""))) {
						listModel2.addElement(listModel.getElementAt(i).toString().replace(users.getSelectedValues()[j].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + ";@<-toUser@@message->@;", ""));
					} else if(listModel.getElementAt(i).toString().startsWith(users.getSelectedValues()[j].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + ";@<-toUser@@message->@;" + "You")) {
						listModel2.addElement(listModel.getElementAt(i).toString().replace(users.getSelectedValues()[j].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + ";@<-toUser@@message->@;", ""));
					}
				}
			}
		}
		list.ensureIndexIsVisible(listModel2.getSize() - 1);
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == msg) {
			sendMsg.doClick();
		}
		if(e.getSource() == sendMsg) {
			if(!msg.getText().equals(""))
			{
				if(!users.isSelectionEmpty()) {
					for(int i = 0; i < users.getSelectedValues().length; i++) {
							main.c.send("XIM_SEND " + users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + "\n" + msg.getText());
							System.out.println("Sending: " + "XIM_SEND " + users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + "\n" + msg.getText());
							listModel.addElement(users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + ";@<-toUser@@message->@;" + "You@" + users.getSelectedValues()[i].toString().replace(" - No Friend", "").replace(" - Online","").replace(" - Offline", "").replace(" - New Message", "") + ": " + msg.getText());
							drawChatList();
					}
						msg.setText("");
				} else {
					System.out.println("No Receiving user selected!");
					JOptionPane.showMessageDialog(null, "You have to select a friend to send to first!\nUse the list on the right!", "Select User!", 0, null);
				}
			} else {
				System.out.println("Message empty!");
				JOptionPane.showMessageDialog(null, "You cannot send an empty message!\nPlease write a message first", "No message!", 0, null);
			}
		}
		if(e.getSource() == exitChat) {
			//main.c.send("XIM_CLOSE");
			main.c.close();
			System.out.println("Exitting Chat");
			System.exit(0);
		}
		if(e.getSource() == removeFriend) {
			if(!users.isSelectionEmpty()) {
				map.remove(users.getSelectedValue().toString().replace(" - No Friend", "").replace(" - Offline","").replace(" - Online","").replace(" - New Message", ""));
				System.out.println("Removing User " + users.getSelectedValue().toString().replace(" - No Friend", "").replace(" - Offline","").replace(" - Online","").replace(" - New Message", ""));
				
				String buddyStr = data.getProperty(LoginWindow.username.getText() + "_ximBuddies");
				String[] buddies = buddyStr.split(";");
				String newBuddyStr = "";
				
				for(int i = 0; i < buddies.length; i++) {
					if(!buddies[i].equals(users.getSelectedValue().toString().replace(" - No Friend", "").replace(" - Offline","").replace(" - Online","").replace(" - New Message", ""))) {
						newBuddyStr = newBuddyStr + buddies[i];
						if(i != buddies.length - 1) {
							newBuddyStr = newBuddyStr + ";";
						}
					}
				}
				
				System.out.println("New Buddy String: " + newBuddyStr);
				data.setProperty(LoginWindow.username.getText() + "_ximBuddies", newBuddyStr);
				
				xim.buddies = data.getProperty(LoginWindow.username.getText() + "_ximBuddies");
				frame.setVisible(false);
				main.c.send("XIM_BUDDIES " + xim.buddies);
				
				redrawUserList(-1);
				drawChatList();
			} else {
				System.out.println("No user to delete selected!");
				JOptionPane.showMessageDialog(null, "You need to select a friend to delete first!\nUse the list on the right!", "Select User!", 0, null);
			}
		}
		if(e.getSource() == addFriend) {
			AddFriend.renderGUI();
			frame.setVisible(false);
		}
	}
}


